package com.lightjet.macross.base.upms.service.impl;

import com.lightjet.macross.base.upms.domain.ApiRules;
import com.lightjet.macross.base.upms.repository.ApiRulesRepository;
import com.lightjet.macross.base.upms.service.ApiRulesService;
import com.lightjet.macross.common.core.BaseServiceImpl;
import com.lightjet.macross.common.dto.ResponseDTO;
import com.lightjet.macross.common.util.RedisUtil;
import com.lightjet.macross.common.util.RespUtil;
import lombok.extern.java.Log;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.List;

@Service("apiRulesServiceImpl")
@Log
public class ApiRulesServiceImpl extends BaseServiceImpl<ApiRules,Integer> implements ApiRulesService {

    @Resource
    private AntPathMatcher antPathMatcher;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public List<ApiRules> FindByFilters(String servicename, String apiuri, String clients) {
        return ((ApiRulesRepository) baseRepository).findByFilters(servicename,apiuri,clients);
    }

    @Override
    public ApiRules FindByServicenameAndApiuri(String servicename, String apiuri) {
        return ((ApiRulesRepository) baseRepository).findByServicenameAndApiuri(servicename,apiuri);
    }

    @Override
    public ApiRules FindDistinctById(Integer id) {
        return ((ApiRulesRepository) baseRepository).findDistinctById(id);
    }

    @Override
    public List<ApiRules> FindByServicenameAndIsenableAndRuletype(String servicename, byte isenable, byte ruletype) {
        return ((ApiRulesRepository) baseRepository).findByServicenameAndIsenableAndRuletype(servicename,isenable,ruletype);
    }

    @Override
    @Cacheable(value = "app_apirules", key = "'uri:'+#servicename+#acturi") //, unless = "#result eq null")
    public ApiRules FindByUri(String servicename, String acturi) {
        List<ApiRules> rules = FindByServicenameAndIsenableAndRuletype(servicename,(byte)1,(byte)1);
        if(rules==null || rules.size() == 0)
        {
            return null;
        }
        else
        {
            for(ApiRules apiRules : rules)
            {
                if(antPathMatcher.match(servicename + apiRules.getApiuri(), servicename + acturi )){
                    return  apiRules;
                }
            }
            return null;
        }
    }

    @Override
    public ResponseDTO<String> ClearRuleCache() {
        if(redisUtil!=null)
        {
            redisUtil.DeleteKeys("app_apirules::uri:*");
            log.info("删除所有app_apirules::uri 缓存");
            return RespUtil.CreateOK();
        }
        else
        {
            return RespUtil.CreateError("RedisUtil未注入");
        }
    }
}
